﻿using Digitalmes.Core.Models;

namespace Digitalmes.Core.Remotes.QcReworks;

/// <summary>
/// 质量返工远端接口。
/// </summary>
public sealed class QcReworkRemoteApi(IHttpClientFactory httpClientFactory, IConfiguration configuration, ILogger<QcReworkRemoteApi> logger) : IRemoteApi
{
    /// <summary>
    /// 获取远端条码信息。
    /// </summary>
    /// <param name="barcode">要查询的条码</param>
    /// <returns></returns>
    public async Task<(bool, ApiResult<QcReworkDto>?, Exception?)> GetBarcodeInfoAsync(string barcode)
    {
        var client = httpClientFactory.CreateClient("MES");
        string endpoint = configuration["RestHttp:MES:Endpoint:GetBarcodeInfo"] ?? "";
        string requestUri = $"{endpoint}/{barcode}";
        logger.LogInformation("HTTP 请求，基地址：{BaseAddress}，请求地址：{RequestUri}", client.BaseAddress, requestUri);

        var (ok, result, err) = await client.TryGetJsonAsync<ApiResult<QcReworkDto>>(requestUri);
        if (ok)
        {
            logger.LogInformation("HTTP 响应成功，响应数据：{@Result}", result);
        }
        else
        {
            logger.LogError("HTTP 响应错误，错误：{Error}", err?.Message);
        }

        return (ok, result, err);
    }

    /// <summary>
    /// 请求返工。
    /// </summary>
    /// <param name="input">请求的参数</param>
    /// <returns></returns>
    public async Task<(bool, ApiResult<bool>?, Exception?)> ReworkAsync(QcReworkInput input)
    {
        var client = httpClientFactory.CreateClient("MES");
        string requestUri = configuration["RestHttp:MES:Endpoint:Rework"] ?? "";
        logger.LogInformation("HTTP 请求，基地址：{BaseAddress}，请求地址：{RequestUri}，请求数据：{@Input}", client.BaseAddress, requestUri, input);

        var (ok, result, err) = await client.TryPostJsonAsync<QcReworkInput, ApiResult<bool>>(requestUri, input);
        if (ok)
        {
            logger.LogInformation("HTTP 响应成功，响应数据：{@Result}", result);
        }
        else
        {
            logger.LogError("HTTP 响应错误，错误：{Error}", err?.Message);
        }

        return (ok, result, err);
    }
}
